package com.cxl.controller;

import com.cxl.entity.Coupon;
import com.cxl.entity.UserCoupon;
import com.cxl.entity.Users;
import com.cxl.repository.CouponRepository;
import com.cxl.repository.UsersRepository;
import com.cxl.service.UserService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author: 20971
 * @time: 2022/3/3 21:03
 * @description:
 */
@RestController
@RequestMapping(value = "/ec/users")
public class UserController {

    @Autowired
    private UserService userService;


    @GetMapping(value = "/list")
    public Page<Users> testQueryList(Users users, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize) {
        Page<Users> page = userService.queryList(users, pageNum, pageSize);
        List<Users> content = page.getContent();
        for (Users u : content) {
            List<UserCoupon> list = u.getUserCoupons();
            String couponName = "";
            for (UserCoupon userCoupon : list) {
                couponName = couponName + "," + userCoupon.getCoupon().getContent();
            }
            u.setCouponName(couponName.substring(0));
        }
        return page;
    }

    @Autowired
    private CouponRepository couponRepository;

    @GetMapping(value = "/getcoupons")
    public List<Coupon> couponList() {
        return couponRepository.findAll();
    }


    /*添加*/
    @PostMapping(value = "/add")
    public void add(@RequestBody Users users) {
        if (users.getId() != null) {
            userService.del(users.getId());
        }
        List<UserCoupon> coupons = new ArrayList<>();
        System.out.println(users);
        for (Integer integer : users.getUserCouponids()) {
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setStatus(1);
            userCoupon.setCoupon(couponRepository.getById(integer));
            userCoupon.setUsers(users);
            coupons.add(userCoupon);
        }
        users.setUserCoupons(coupons);
        userService.save(users);
    }

}
